from django import template 
 from util import parse_args_kwargs_as_var_and_with_var
 from django.template.loader import render_to_string
 from django.template import Template, Context
 
 register = template.Library()
 
 header = '''<div class='boxheader'><div class='headercontent'>%s</div></div>'''
 
 @register.tag(name="box")
 def do_box(parser, token):
     nodelist = parser.parse(('endbox',))
     args, kwargs, as_var, with_var = parse_args_kwargs_as_var_and_with_var(parser, token.split_contents()[1:])
     parser.delete_first_token()
     return BoxNode(args, kwargs, as_var, with_var, nodelist)
 
 class BoxNode(template.Node):
     def __init__(self, args, kwargs, as_var, with_var, nodelist):
         self.with_var = with_var
         self.nodelist = nodelist
         self.mode = 'query' if 'bind_to_query' in kwargs else 'data'
         self.bindto = kwargs.get('bind_to_query', kwargs.get('bind_to_block')).token
         self.autoupdate = True if 'autoupdate' in args else False
         self.headerenabled = True if 'headerenabled' in args else False
         
     def render(self, context):
         return header % get_renderer(self.mode, self.bindto, self.with_var).render(context, self.nodelist)
 
 def get_renderer(mode, name, with_var):
     if (mode == 'query'):
         return QueryRenderer(name, with_var)
     return BlockRenderer(name, with_var)
 
 class QueryRenderer():
     def __init__(self, name, with_var):
         self.name = name
         self.with_var = ",".join([str(a) for a in with_var])
     def render(self, context, nodelist):
         t = Template('''%s runquery name=%s eval_to=context with %s as %s %s''' % ('{%', self.name, self.with_var, 'result', '%}'))
         t.render(context)
         output = nodelist.render(context)
         return output
 
 class BlockRenderer():
     def __init__(self, name, with_var):
         self.name = name
         self.with_var = with_var
     def render(self, context, nodelist):
         context['with_var'] = self.with_var
         return render_to_string('%s.html'% self.name, context)